import 'dart:convert';
import 'dart:io';

import 'package:animal/constant/font.dart';
import 'package:animal/socket/base.dart';
import 'package:animal/socket/base_model.dart';
import 'package:animal/socket/socket_client.dart';
import 'package:animal/socket/socket_message_model/friend_message_model.dart';
import 'package:animal/socket/type_model.dart';
import 'package:animal/utils/DBUtil.dart';
import 'package:animal/utils/screen_util.dart';
import 'package:animal/utils/sputils/sp_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:image_picker/image_picker.dart';

class MessageDetailController extends GetxController {
  UserModel? friendModel;

  final EasyRefreshController refreshController = EasyRefreshController();
  final TextEditingController textEditingController = TextEditingController();

  // 滚动控制器
  ScrollController? scrollController;

  DBUtil? dbUtil;

  final ClientSocket clientSocket = Get.find();

  var entitys = <MessageEntity>[].obs;

  var a = [1, 2, 3];

  var box = Hive.box('messageBox');

  var data = <FriendMessageModel>[].obs;

  var userInfo = jsonDecode(SpConfig().getUserInfo()!);

  @override
  void onInit() {
    super.onInit();
    entitys.add(MessageEntity(true, "It's good!"));
    entitys.add(MessageEntity(false, 'EasyRefresh'));
    scrollController = ScrollController();
    init();
  }

  Future<void> init() async {
    dbUtil = await DBUtil.getInstance();
  }

  ///发送文字消息
  void sendTextMessage() async {
    if (textEditingController.text.isNotEmpty) {
      String model = await BaseModel()
          .textMessageData(
            content: textEditingController.text,
            tid: int.parse(friendModel!.id!),
            userModel: UserModel(id: userInfo["id"].toString(), name: userInfo["nickName"]),
          )
          .then((value) => jsonEncode(value) + SocketBase.lastString);
      debugPrint(model);
      //存储IM发送的数据
      box.add(jsonDecode(model.replaceAll("\$qwer\$", "")));
      //发送消息
      clientSocket.glSock!.write(model);
      textEditingController.clear();
      entitys.insert(0, MessageEntity(true, textEditingController.text));
      scrollController!.animateTo(0.0, duration: const Duration(milliseconds: 300), curve: Curves.linear);
    }
  }

  ///发送图片消息
  void imageMessage() async{
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    List<int> bytes =await image!.readAsBytes();
    String model = await BaseModel()
        .textMessageData(
      content: base64Encode(bytes),
      tid: int.parse(friendModel!.id!),
      userModel: UserModel(id: userInfo["id"].toString(), name: userInfo["nickName"]),
    )
        .then((value) => jsonEncode(value) + SocketBase.lastString);
    debugPrint(model);
    //存储IM发送的数据
    box.add(jsonDecode(model.replaceAll("\$qwer\$", "")));
    clientSocket.glSock!.write(model);
    debugPrint(image.path);
  }

  /// 计算内容的高度
  double calculateMsgHeight(BuildContext context, BoxConstraints constraints, MessageEntity entity) {
    return ScreenUtil().L(45) +
        calculateTextHeight(
          context,
          constraints,
          text: '我',
          textStyle: KFontConstant.myTextStyle(size: 15),
        ) +
        calculateTextHeight(
          context,
          constraints.copyWith(
            maxWidth: ScreenUtil().L(200),
          ),
          text: entity.msg,
          textStyle: KFontConstant.myTextStyle(size: 15),
        );
  }

  /// 计算Text的高度
  double calculateTextHeight(
    BuildContext context,
    BoxConstraints constraints, {
    String text = '',
    required TextStyle textStyle,
    List<InlineSpan> children = const [],
  }) {
    final span = TextSpan(text: text, style: textStyle, children: children);

    final richTextWidget = Text.rich(span).build(context) as RichText;
    final renderObject = richTextWidget.createRenderObject(context);
    renderObject.layout(constraints);
    return renderObject.computeMinIntrinsicHeight(constraints.maxWidth);
  }

  ///获取消息信息
  void getMessage(){
    for(int i = 0;i<box.length;i++){
      if(box.getAt(i)["m"]["f"] == userInfo["id"] || box.getAt(i)["m"]["t"] == userInfo["id"]){
        data.add(FriendMessageModel.fromJson(box.getAt(i)));
      }
    }
  }
}

/// 信息实体
class MessageEntity {
  bool own;
  String msg;

  MessageEntity(this.own, this.msg);
}
